package android.framework.rpc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import android.framework.rpc.convertor.ConvertorHelper;
import android.framework.rpc.convertor.JsonConvertor;
import android.framework.rpc.convertor.ObjectConvertor;

public class ProxyInvokeHandler<TIContract> implements InvocationHandler{
	private IProtocolManager<String> protocolManager;
	private ConvertorHelper<Object,String> convertorHelper;
	
	public ProxyInvokeHandler(ServerDetails serverDetails){
		protocolManager = new DefaultProtocolManager<String>(new HttpSender(), serverDetails);
		convertorHelper = new ConvertorHelper<Object, String>(new ObjectConvertor(), new JsonConvertor());
	}
	
	@SuppressWarnings("unchecked")
	public static <TIContract> TIContract CreateInstace(Class<TIContract> contract, ServerDetails serverDetails){
		Class<?>[] classes = new Class[1]; 
        classes[0] = contract;
        TIContract proxy = (TIContract)Proxy.newProxyInstance(contract.getClassLoader(),
                                                 classes,
                                                 new ProxyInvokeHandler<TIContract>(serverDetails));
        return proxy;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		MethodCall methodCall = new MethodCall(method.getName(), args);
		
		String sendingData = convertorHelper.convertFrom(methodCall);
		Request<String> request = new Request<String>(sendingData);
		String response = protocolManager.sendNewRequest(request);
		return convertorHelper.convertTo(response);
	}
	
}
